<template>
  <div id="app" class="chat-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>即时通讯在线聊天</span>
      </div>

      <el-input v-model="url" placeholder="WebSocket URL" style="width: 70%; margin-bottom: 10px;"></el-input>
      <el-input v-model="userId" placeholder="输入用户 ID" style="width: 70%; margin-bottom: 10px;"></el-input>
      <el-button type="primary" @click="connectWebSocket">连接</el-button>
      <el-button type="danger" @click="disconnectWebSocket">断开</el-button>

      <el-input v-model="targetUserId" placeholder="目标用户 ID" style="width: 70%; margin-top: 10px;"></el-input>

      <div class="chat-window" ref="chatWindow">
        <div v-for="(message, index) in messages" :key="index" class="message">
          <el-tag type="info" class="message-content">{{ message }}</el-tag>
        </div>
      </div>

      <el-input v-model="message" placeholder="输入消息..." @keyup.enter="sendMessage"></el-input>
      <el-button type="success" @click="sendMessage">发送</el-button>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      url: "ws://127.0.0.1:8080/websocket/message/", // 默认 WebSocket 地址
      userId: "", // 当前用户的 ID
      targetUserId: "", // 目标用户的 ID
      ws: null, // WebSocket 对象
      message: "", // 当前输入的消息
      messages: [] // 消息记录
    };
  },
  methods: {
    // 连接 WebSocket
    connectWebSocket() {
      if (this.ws) {
        this.$message({ type: 'warning', message: '连接已存在!' });
        return;
      }
      if (this.userId.trim() === "") {
        this.$message({ type: 'warning', message: '请先输入用户 ID!' });
        return;
      }
      this.ws = new WebSocket(`${this.url}${this.userId}`);
      this.ws.onopen = () => {
        this.$message({ type: 'success', message: '连接成功!' });
        this.messages.push("已经打开连接!");
      };
      this.ws.onmessage = (event) => {
        this.messages.push(event.data);
        this.$nextTick(() => {
          // 滚动到底部
          this.$refs.chatWindow.scrollTop = this.$refs.chatWindow.scrollHeight;
        });
      };
      this.ws.onclose = () => {
        this.$message({ type: 'warning', message: '连接已关闭!' });
        this.messages.push("已经关闭连接!");
        this.ws = null;
      };
      this.ws.onerror = (error) => {
        this.$message({ type: 'error', message: '连接发生错误!' });
        console.error('WebSocket 错误: ', error);
        this.ws = null;
      };
    },
    // 断开 WebSocket
    disconnectWebSocket() {
      if (this.ws) {
        if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
          this.ws.close();
        }
        this.ws = null;
      } else {
        this.$message({ type: 'info', message: '没有连接可断开!' });
      }
    },
    // 发送消息
    sendMessage() {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        if (this.message.trim() !== "" && this.targetUserId.trim() !== "") {
          const fullMessage = JSON.stringify({
            to: this.targetUserId,
            message: this.message
          });
          this.ws.send(fullMessage);
          this.messages.push(`我对 ${this.targetUserId}: ${this.message}`);
          this.message = "";
        } else {
          this.$message({ type: 'warning', message: '请先输入目标用户 ID 和消息!' });
        }
      } else {
        this.$message({ type: 'warning', message: '请先建立连接!' });
      }
    }
  }
};
</script>

<style scoped>
.chat-container {
  width: 600px;
  margin: 30px auto;
}
.chat-window {
  height: 300px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  padding: 10px;
  margin-bottom: 10px;
  background-color: #f9f9f9;
}
.message {
  margin-bottom: 10px;
}
.message-content {
  word-break: break-all;
}
</style>